package com.hlx.project.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.plugins.pagination.PageDTO;
import com.hlx.project.common.BaseResponse;
import com.hlx.project.common.ErrorCode;
import com.hlx.project.common.ResultUtils;
import com.hlx.project.exception.BusinessException;
import com.hlx.project.model.dto.team.*;
import com.hlx.project.model.entity.Team;
import com.hlx.project.model.entity.User;
import com.hlx.project.model.vo.TeamUserVO;
import com.hlx.project.service.TeamService;
import com.hlx.project.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 队伍接口
 *
 * @author hlx
 */
@RestController
@RequestMapping("/team")
@Api(tags = "队伍管理")
@CrossOrigin
@Slf4j
public class TeamController {

    @Resource
    private TeamService teamService;

    @Resource
    private UserService userService;

    // region 增删改查

    /**
     * 创建用户
     *
     * @param teamAddRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "创建队伍")
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request) {
        if (teamAddRequest == null || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest, team);
        User loginUser = userService.getLoginUser(request);
        return ResultUtils.success(teamService.addTeam(team, loginUser));
    }

    /**
     * 删除用户
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "删除队伍")
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody TeamDeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long currentUserId = userService.getLoginUser(request).getId();
        Long teamUserId = deleteRequest.getUserid();
        if (Objects.equals(teamUserId, currentUserId) || userService.isAdmin(request)) {
            boolean b = teamService.removeById(deleteRequest.getId());
            return ResultUtils.success(b);
        } else {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
    }

    /**
     * 更新用户
     *
     * @param teamUpdateRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "更新队伍")
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest teamUpdateRequest, HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        if (teamUpdateRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean b = teamService.updateTeam(teamUpdateRequest, request);
        return ResultUtils.success(b);
    }

    /**
     * 根据 id 获取用户
     *
     * @param id
     * @param request
     * @return
     */
    @ApiOperation(value = "获取队伍")
    @GetMapping("/get")
    public BaseResponse<TeamUserVO> getTeamById(int id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        TeamUserVO teamVO = new TeamUserVO();
        BeanUtils.copyProperties(team, teamVO);
        return ResultUtils.success(teamVO);
    }

    /**
     * 获取用户列表
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "获取队伍列表")
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeam(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        if (teamQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        boolean admin = userService.isAdmin(request);
        List<TeamUserVO> list = teamService.listTeam(teamQueryRequest, admin);
        return ResultUtils.success(list);
    }

    /**
     * 分页获取用户列表
     *
     * @param teamQueryRequest
     * @param request
     * @return
     */
    @ApiOperation(value = "分页获取队伍")
    @GetMapping("/list/page")
    public BaseResponse<Page<TeamUserVO>> listTeamByPage(TeamQueryRequest teamQueryRequest, HttpServletRequest request) {
        long current = 1;
        long size = 10;
        Team teamQuery = new Team();
        if (teamQueryRequest != null) {
            BeanUtils.copyProperties(teamQueryRequest, teamQuery);
            current = teamQueryRequest.getCurrent();
            size = teamQueryRequest.getPageSize();
        }
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(teamQuery);
        Page<Team> teamPage = teamService.page(new Page<>(current, size), queryWrapper);
        Page<TeamUserVO> teamVOPage = new PageDTO<>(teamPage.getCurrent(), teamPage.getSize(), teamPage.getTotal());
        List<TeamUserVO> teamVOList = teamPage.getRecords().stream().map(team -> {
            TeamUserVO teamVO = new TeamUserVO();
            BeanUtils.copyProperties(team, teamVO);
            return teamVO;
        }).collect(Collectors.toList());
        teamVOPage.setRecords(teamVOList);
        return ResultUtils.success(teamVOPage);
    }

    // endregion


    @PostMapping("/join")
    @ApiOperation("加入队伍")
    public BaseResponse<Boolean> joinTeam(TeamJoinRequest teamJoinRequest, HttpServletRequest request) {
        if (teamJoinRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if (request == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(teamService.joinTeam(teamJoinRequest, request));
    }
    
    @PostMapping("/quit")
    @ApiOperation("退出队伍")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest teamQuitRequest, HttpServletRequest request) {
        if(teamQuitRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        if(request == null) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        return ResultUtils.success(teamService.quitTeam(teamQuitRequest,request));
    }

    @GetMapping("/list/my/create")
    @ApiOperation("获取创建队伍")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        teamQuery.setUserId(loginUser.getId());
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, true);
        return ResultUtils.success(teamList);
    }

}
